package ru.reaperoq.inventory.screens.auth

import LoadingStatus
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import org.koin.androidx.compose.navigation.koinNavViewModel
import register.RegisterViewModel
import register.models.RegisterEvent
import ru.reaperoq.inventory.components.textField.LoginTextField
import ru.reaperoq.inventory.components.textField.PasswordTextField

@Composable
fun RegisterScreen(
    modifier: Modifier = Modifier,
    viewModel: RegisterViewModel = koinNavViewModel(),
    onLoginClick: () -> Unit,
    onRegister: () -> Unit
) {
    val viewState by viewModel.viewStates().collectAsState()
    val keyboardController = LocalSoftwareKeyboardController.current
    val context = LocalContext.current

    LaunchedEffect(viewState.loadingStatus) {
        if (viewState.loadingStatus == LoadingStatus.FullyLoad) {
            onRegister()
        }
        if (viewState.loadingStatus is LoadingStatus.Error) {
            Toast.makeText(
                context,
                (viewState.loadingStatus as LoadingStatus.Error).message ?: "Ошибка авторизации",
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    val passwordMatches by with(viewState) {
        remember(
            password,
            passwordConfirmation
        ) { mutableStateOf(password.isEmpty() || passwordConfirmation.isEmpty() || (password == passwordConfirmation)) }
    }

    Column(
        modifier = modifier.fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(8.dp, alignment = Alignment.CenterVertically),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        LoginTextField(
            value = viewState.username,
            onValueChange = { viewModel.obtainEvent(RegisterEvent.UsernameChanged(it)) },
            enabled = viewState.loadingStatus != LoadingStatus.Loading
        )
        PasswordTextField(
            value = viewState.password,
            onValueChange = { viewModel.obtainEvent(RegisterEvent.PasswordChanged(it)) },
            enabled = viewState.loadingStatus != LoadingStatus.Loading,
        )
        PasswordTextField(
            value = viewState.passwordConfirmation,
            onValueChange = { viewModel.obtainEvent(RegisterEvent.PasswordConfirmationChanged(it)) },
            enabled = viewState.loadingStatus != LoadingStatus.Loading,
            labelText = "Подтвердите пароль",
            error = if (passwordMatches) null else "Пароли должны совпадать"
        ) {
            keyboardController?.hide()
            viewModel.obtainEvent(RegisterEvent.RegisterClicked)
        }
        Button(
            onClick = {
                keyboardController?.hide()
                viewModel.obtainEvent(RegisterEvent.RegisterClicked)
            },
            enabled = viewState.loadingStatus != LoadingStatus.Loading && passwordMatches &&
                    viewState.username.isNotBlank() && viewState.password.isNotBlank() && viewState.passwordConfirmation.isNotBlank()
        ) {
            if (viewState.loadingStatus == LoadingStatus.Loading) {
                CircularProgressIndicator()
            } else {
                Text("Регистрация")
            }
        }
        Text(
            text = buildAnnotatedString {
                withStyle(
                    style = SpanStyle(
                        color = MaterialTheme.colorScheme.primary,
                        textDecoration = TextDecoration.Underline
                    )
                ) {
                    append("Есть аккаунт?")
                }
            },
            modifier = Modifier
                .padding(8.dp)
                .clip(MaterialTheme.shapes.extraLarge)
                .clickable(onClick = onLoginClick)
        )
    }
}